  <template>
  <div class="update-photo">
    <img class="img" :src="img" ref="img" />

    <div class="toolbar">
      <div class="cancel" @click="$emit('close')">取消</div>
      <div class="confirm" @click="onConfirm">完成</div>
    </div>
  </div>
</template>

<script>
import "cropperjs/dist/cropper.css";
import Cropper from "cropperjs";
import { updateUserPhoto } from "@/api/user.js";
export default {
  name: "UpdatePhoto",
  components: {},
  props: {
    img: {
      type: [String, Object],
      required: true,
    },
  },
  data() {
    return { cropper: null };
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {
    const image = this.$refs.img;
    this.cropper = new Cropper(image, {
      viewMode: 1, //将裁剪框限制为画布的大小
      dragMode: "move", //默认为crop模式,none画布拖不了，截图可以拖
      aspectRatio: 1, //头像比例，默认为16/9
      autoCropArea: 1, //裁剪区域会自动撑满整个画布的大小
      cropBoxMovable: false, //只需要画布移动，不需要裁剪区域移动，因此设置为false
      cropBoxResizable: true, //截图区域的缩放关掉
      background: false, //不要背景色
    });
  },
  methods: {
    onConfirm() {
      // 第一种方式：基于服务端的裁切使用 getData 方法获取裁切参数，传到后端，让后端进行裁剪
      // console.log(this.cropper.getData());
      //第二种方式 纯客户端的裁切使用 getCroppedCanvas 获取裁切的文件对象
      this.cropper.getCroppedCanvas().toBlob(async (blob) => {
        this.updateUserPhoto(blob);
      });
    },

    async updateUserPhoto(blob) {
      this.$toast.loading({
        message: "头像上传中...",
        forbidClick: true, //禁止点击背景；
        loadingType: "spinner",
        duration: 0, //持续时间
      });
      try {
        const formData = new FormData();
        formData.append("photo", blob);
        const { data } = await updateUserPhoto(formData);
        // 关闭弹层，更新视图
        this.$emit("close");
        this.$emit("update-avatar", data.data.photo);
        this.$toast("更新成功");
      } catch (err) {
        this.$toast("更新失败");
      }
    },
  },
};
</script>

<style scoped lang="less">
.update-photo {
  background-color: #000;
  height: 100%;
  .toolbar {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    justify-content: space-between;
    .cancel,
    .confirm {
      width: 90px;
      height: 90px;
      font-size: 30px;
      display: flex;
      justify-content: center;
      align-items: center;
      color: #fff;
    }
  }
}
.img {
  display: block;
  max-width: 100%;
}
</style>